<template>
  <div class="app-container">
    <!--区域数据-->
    <el-col :span="4" style="height: 100%;padding-left: 0;">
      <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
        <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                  style="width: 100%;" v-model="filterText"/>
        <div style="height: 96%; max-height:96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
          <el-tree
            :data="sheetsTreeList"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            :default-expanded-keys="defaultExpandedKeys"
            highlight-current
            v-loading="treeLoading"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data}">
              <div class="custom-tree-node" style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                <span>{{ node.label }}</span>
                <!-- <span v-if="data.deviceCount!=null" class="device-count">({{data.deviceCount}})</span> -->
              </div>
            </template>
          </el-tree>
        </div>
      </div>
    </el-col>
    <el-col :span="20" style="height: 100%;background-color: #FFFFFF;padding: 10px;">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="公摊名称" prop="publicShareName">
          <el-input
            v-model="queryParams.publicShareName"
            placeholder="请输入公摊名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="userId">
          <el-select v-model="queryParams.userId" placeholder="请选择用户名称" filterable clearable>
            <el-option v-for="user in userList"
              :key="user.userId"
              :label="user.userId + '-' +user.userName"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="能源类型" prop="energyType">
          <el-select v-model="queryParams.energyType" placeholder="请选择能源类型" @change="handleChange1">
            <el-option v-for="dict in dict.type.energy_use_classification"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['datastatistics:publicShare:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['datastatistics:publicShare:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['datastatistics:publicShare:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="((queryParams.userId === '' || queryParams.userId === null) || multiple)"
            @click="handleGuohu"
          >一键过户</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['datastatistics:publicShare:export']"
          >导出</el-button>
        </el-col> -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="publicShareList" row-key="id" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="公摊编号" align="center" prop="id" width="80"/>
        <!-- <el-table-column label="租户号" align="center" prop="tenantId" /> -->
        <el-table-column label="所属区域" align="center" prop="areaId" width="140">
          <template slot-scope="scope">
            {{getAreaName(scope.row.areaId)}}
          </template>
        </el-table-column>
        <el-table-column label="公摊名称" align="center" prop="publicShareName" />
        <el-table-column label="能耗类型" align="center" prop="energyType" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.energy_use_classification" :value="scope.row.energyType"/>
          </template>
        </el-table-column>
        <!-- <el-table-column label="挂接用户" align="center" prop="gjUserIds" :show-overflow-tooltip="true">
          <template slot-scope="scope">
              <div>{{scope.row.gjUserIds != null && scope.row.gjUserIds != '' ? scope.row.gjUserIds : '/'}}</div>
            </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['datastatistics:publicShare:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleSetting(scope.row)"
              v-hasPermi="['datastatistics:publicShare:edit']"
            >挂接</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['datastatistics:publicShare:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-col>

    

    <!-- 添加或修改公摊配置表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="区域" prop="areaId">
          <treeselect v-model="form.areaId" :options="sheetsTreeList" :normalizer="normalizer"
                      :show-count="true"
                      placeholder="请选择区域名称"
                      @select="handleSheetsChange"
                      :disable-branch-nodes="false" >
            <template v-slot:option-label="{ node, shouldShowCount, count }">
            <span>
              <!-- 这里添加你的图标，可以是字体图标或图片 -->
              <!-- <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="node.raw.deviceType === 0"></span>
              <span class="iconfont icon-loudong icon-padding" v-if="node.raw.deviceType === 1"></span>
              <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="node.raw.deviceType === 2"></span> -->
              {{ node.label }}
              <!-- 如果需要，可以显示选中的数量 -->
              <!-- <span v-if="shouldShowCount">({{ count }})</span> -->
            </span>
            </template>
          </treeselect>
        </el-form-item>
        <!-- <el-form-item label="租户号" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入租户号" />
        </el-form-item>
        <el-form-item label="区域主键" prop="areaId">
          <el-input v-model="form.areaId" placeholder="请输入区域主键" />
        </el-form-item> -->
        <el-form-item label="公摊名称" prop="publicShareName">
          <el-input v-model="form.publicShareName" placeholder="请输入公摊名称" />
        </el-form-item>
        <el-form-item label="能源类型" prop="energyType" key="energyType">
          <el-select v-model="form.energyType" placeholder="请选择能源类型" clearable style="width: 100%;">
            <el-option v-for="dict in dict.type.energy_use_classification"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="addr">
          <el-input v-model="form.addr" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 挂接 -->
    <el-dialog :title="setTitle" :visible.sync="setOpen"
    :fullscreen="isFullscreen" append-to-body  :show-close="false"
    width="1180px" :close-on-click-modal="false" >
     
    <template #title>
         <div class="custom-dialog-header">
          <!-- 原始标题 -->
          <span  class="custom-dialog-title" >{{ setTitle }}</span>
          <div class="custom-dialog-actions">
          <el-button
              type="text"
              size="mini"
              class="custom-dialog-btn"
              @click.stop="toggleMaximize"
            >
              <i :class="isFullscreen ? 'el-icon-minus' : 'el-icon-full-screen'"></i>
            </el-button>

            <el-button
              type="text"
              size="mini"
              class="custom-dialog-btn custom-dialog-close-btn"
              @click.stop="setOpen = false"
            >
              <i class="el-icon-close"></i>
            </el-button>
              </div>
        </div>
      </template>
      <div  :class="[isFullscreen ? 'div-height-full-screen':'div-height-minus']">
        <el-form ref="setForm" label-width="0px" style="display: flex;"> 
          

          <el-form-item label="" prop="" style="margin-left: 10px;">
            <el-select v-model="powerType" placeholder="请选择" disabled style="width: 200px" 
            @change="handleEnergyTypeChange">
              <el-option v-for="dict in dict.type.energy_use_classification"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>

            <el-form-item label="" prop="" style="margin-left: 10px;">
             <el-select clearable filterable v-model="publicShareType" placeholder="请选择公摊类别"  
             @change="handlePublicShareTypeChange"
             style="width: 200px" >
               <el-option 
                label="" 
                value=""
               ></el-option>
              <el-option v-for="dict in dict.type.public_share_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="" prop="" style="margin-left: 10px;">
            <el-input v-model="userId"
             @change="handleUserIdChange"
            placeholder="请输入用户编号" clearable />
          </el-form-item>

          <el-form-item label="" prop="" style="margin-left: 10px;">
            <el-input v-model="terminalId"
             @change="handleTerminalIdChange"
            placeholder="请输入设备编号" clearable />
          </el-form-item>



          <el-form-item label="" prop="" style="margin-left: 10px;">
            <el-button type="primary" :disabled="!publicShareType" plain icon="el-icon-plus" @click="handleTerminalAdd" >新增</el-button>
          </el-form-item>

          <!-- <el-form-item label="" prop=""  style="margin-left: 10px;">
            <el-button type="primary" plain icon="el-icon-plus" @click="handleTerminalAddConstant" >新增常量</el-button>
          </el-form-item> -->



        </el-form>
        <el-table v-loading="setLoading" :data="setDataList" size="mini" row-key="id" border height="calc(100% - 100px)">
          <el-table-column label="用户名称" align="center" prop="userName" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <div v-if="scope.row.publicShareType === 3 ">/</div>
               <div v-else>{{ scope.row.userName }}</div>
            </template>

          </el-table-column>
          <el-table-column label="用户编号" align="center" prop="userId" width="100" >
             <template slot-scope="scope">
              <div v-if="scope.row.publicShareType === 3 ">/</div>
               <div v-else>{{ scope.row.userId }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="publicShareType == 1" label="设备编号" align="center" prop="terminalId" width="110" />
          <!-- <el-table-column label="设备编号" align="center" prop="terminalId" width="100" /> -->
          <!-- <el-table-column label="能耗类型" align="center" prop="energyType" width="80" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.energy_use_classification" :value="scope.row.energyType+''"/>
            </template>
          </el-table-column> -->
          <el-table-column label="公摊类别" align="center" prop="publicShareType" width="170" >
            <template slot-scope="scope">
              <el-select :disabled ="scope.row.publicShareType ===3 "  v-model="scope.row.publicShareType" placeholder="请选择" style="width: 100%" @change="handleEditChange(scope.row)">
                <el-option v-for="dict in dict.type.public_share_type" :key="dict.value" :label="dict.label"
                          :disabled="dict.value == 3 "
                          :value="parseInt(dict.value)"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="公摊计算类型" align="center" prop="calcType" width="100">
            <template slot-scope="scope">
              <el-select v-if="scope.row.publicShareType === 1 || scope.row.publicShareType === 3" v-model="scope.row.calcType" 
              placeholder="请选择" style="width: 100%" 
              @change="handleEditChange(scope.row)">
                <el-option v-for="dict in dict.type.public_share_calc_type" :key="dict.value" :label="dict.label"
                         
                          :value="parseInt(dict.value)"></el-option>
              </el-select>
              <div v-else>/</div>
            </template>
          </el-table-column>

          <el-table-column label="比率/常量值" align="center" prop="calcRate" width="230">
            <template slot-scope="scope">
               <el-input-number
                      v-model="scope.row.calcRate" 
                      :precision="4"
                       @change.native="handleEditChange(scope.row)"
                      :step="0.0001"
                    ></el-input-number>   
            </template>
          </el-table-column>

          <el-table-column label="更改时间" align="center" prop="updateTime" width="150" />
          <el-table-column label="状态" align="center" prop="status" width="100" >
            <template slot-scope="scope">
              <div>{{scope.row.status === 1 ? '在场' : scope.row.status === 2 ? '离场' : '删除'}}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="50">
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="删除" placement="top">
                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleBindTerminalDelete(scope.row)"
                >
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="terminalTotalSetting>0"
          :total="terminalTotalSetting"
          
          :page.sync="terminalQueryParamsSetting.pageNum"
          :limit.sync="terminalQueryParamsSetting.pageSize"
          layout="total, sizes, prev, pager, next"
          @pagination="getBindList"
        />

      </div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div> -->
    </el-dialog>


    <!-- 挂接-新增按钮弹框 -消费-用户 -->
    <el-dialog title="选取用户" :visible.sync="terminalOpen" width="650px" :close-on-click-modal="false" append-to-body>
      <div style="height: 400px;">
        <el-form ref="terminalForm" :model="terminalQueryParams" label-width="70px" style="display: flex;"> 
          <el-form-item label="用户名称" prop="userName">
            <el-input :size="formItemSize" v-model="terminalQueryParams.userName" placeholder="请输入用户名称" clearable />
          </el-form-item>
          <el-form-item label="用户编号" prop="userId" style="margin-left: 10px;">
            <el-input :size="formItemSize" v-model="terminalQueryParams.userId" placeholder="请输入用户编号" clearable />
          </el-form-item>
          <div style="margin-left: 10px;height: 30px;line-height: 36px;">
            <el-button  type="primary" plain icon="el-icon-search" @click="handleTerminalQuery" size="mini">查询</el-button>
          </div>
        </el-form>
        <el-table v-loading="terminalLoading" :data="terminalDataList" size="mini" row-key="id" border height="calc(100% - 102px)"
          @selection-change="handleSelectionChange2">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="用户编号" align="center" prop="userId" width="120" />
          <el-table-column label="用户名称" align="center" prop="userName" min-width="150" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="设备编号" align="center" prop="terminalId" width="120" /> -->
          <!-- <el-table-column label="能耗分类" align="center" prop="energyType" width="100" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.energy_use_classification" :value="powerType+''"/>
            </template>
          </el-table-column> -->
        </el-table>
        <pagination
          v-show="terminalTotal>0"
          :total="terminalTotal"
          pager-count="5"
          :page.sync="terminalQueryParams.pageNum"
          :limit.sync="terminalQueryParams.pageSize"
          layout="total, sizes, prev, pager, next"
          @pagination="getTerminalDataList"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="terminalSubmitForm">确 定</el-button>
        <el-button @click="terminalCancel">取 消</el-button>
      </div>
    </el-dialog>


      <!-- 挂接-新增按钮弹框 生产-设备绑定 -->
    <el-dialog title="选取设备" :visible.sync="terminalOpenProduct" width="650px" :close-on-click-modal="false" append-to-body>
      <div style="height: 400px;">
        <el-form ref="terminalFormProduct" :model="terminalQueryParamsProduct" label-width="70px" style="display: flex;"> 
          <!-- <el-form-item label="用户名称" prop="userName">
            <el-input :size="formItemSize" v-model="terminalQueryParams.userName" placeholder="请输入用户名称" clearable />
          </el-form-item> -->
          <el-form-item label="设备编号" prop="terminalId" style="margin-left: 10px;">
            <el-input :size="formItemSize" v-model="terminalQueryParamsProduct.terminalId" placeholder="请输入设备编号" clearable />
          </el-form-item>
          <div style="margin-left: 10px;height: 30px;line-height: 36px;">
            <el-button  type="primary" plain icon="el-icon-search" @click="handleTerminalQueryProduct" size="mini">查询</el-button>
          </div>
        </el-form>
        <el-table v-loading="terminalLoadingProduct" :data="terminalDataListProduct" size="mini" row-key="id" border height="calc(100% - 102px)"
          @selection-change="handleSelectionChange2Product">
          <el-table-column type="selection" width="55" align="center"/>
         
          <el-table-column label="设备编号" align="center" prop="terminalId" width="120" />
          <el-table-column label="安装地址" align="center" prop="installAddress" min-width="120" /> 
          <!-- <el-table-column label="用户编号" align="center" prop="userId" width="120" />
          <el-table-column label="用户名称" align="center" prop="userName" width="120" :show-overflow-tooltip="true"/> -->

        </el-table>
        <pagination
          v-show="terminalTotalProduct>0"
          :total="terminalTotalProduct"
          pager-count="5"
          :page.sync="terminalQueryParamsProduct.pageNum"
          :limit.sync="terminalQueryParamsProduct.pageSize"
          layout="total, sizes, prev, pager, next"
          @pagination="getTerminalDataListProduct"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="terminalSubmitFormProduct">确 定</el-button>
        <el-button @click="terminalCancelProduct">取 消</el-button>
      </div>
    </el-dialog>




    <!-- 目标用户过户 -->
    <el-dialog title="选择目标过户用户" :visible.sync="guohuOpen" width="300px" append-to-body>
      <el-form ref="guohuForm" :model="guohuForm" :rules="guohuRules" label-width="80px">       
        <el-form-item label="用户名称" prop="targetUserId" key="targetUserId">
          <el-select v-model="guohuForm.targetUserId" placeholder="请选择用户名称" filterable clearable style="width: 100%;">
            <el-option v-for="user in userList"
              :key="user.userId"
              :label="user.userId + '-' +user.userName"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGuohuForm">确 定</el-button>
        <el-button @click="guohuCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {getPublicShare, listPublicShare, addPublicShare,updatePublicShare,delPublicShare,transferPublicShare} from "@/api/basedata/publicShare";
  import {listPublicShareJoinAll,delPublicShareJoin,addBindUser,editBindUser,getUserListInSelect
    ,getUserPageForGJ,getUserPageForGJProduct} from "@/api/basedata/publicShareJoin";
  import { listElecTerminalXb } from "@/api/basedata/elecTerminalXb";
  import { gjListTerminalxb } from "@/api/record/terminalxb";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
  name: "PublicShare",
  components: {Treeselect},
  dicts: ['energy_use_classification','public_share_calc_type','public_share_type'],
  data() {
    return {
      terminalId:"",
      userId:'',
      isFullscreen: false,

      publicShareType:"",
      // 区域树选项
      sheetsTreeList: [],
      defaultProps: {
        children: "children",
        label: "sheetsName",
      },
      filterText: '',
      treeLoading: false,
      treeWidth: '',
      defaultExpandedKeys: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公摊配置表表格数据
      publicShareList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantId: null,
        sheetsCode:null,
        areaId: null,
        publicShareName: null,
        energyType: '1',
        userId:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        areaId: [
          {required: true, message: "请选择区域", trigger: "change"}
        ],
        publicShareName: [
          {required: true, message: "公摊名称不能为空", trigger: "change"}
        ],
        energyType: [
          {required: true, message: "请选择能源类型", trigger: "change"}
        ],
      },
      //挂接
      formItemSize: 'mini', 
      // 弹出层标题
      setTitle: "",
      // 是否显示弹出层
      setOpen: false,
      powerType:'1',
      setLoading:false,
      setDataList:[],
      selectedPublicShareId:null,
      selectedPublicShareName:'',
      terminalOpen:false,

       terminalTotalSetting:0,
      terminalQueryParamsSetting:{
        pageNum: 1,
        pageSize: 20,
        userId:'',
        userName:''
      },


      terminalTotal:0,
      terminalQueryParams:{
        pageNum: 1,
        pageSize: 20,
        userId:'',
        userName:''
      },
      terminalLoading:false,
      terminalDataList:[],
      selectedTerminalList:[],

      terminalOpenProduct:false,
      terminalTotalProduct:0,
      terminalQueryParamsProduct:{
        pageNum: 1,
        pageSize: 20,
        userId:'',
        userName:''
        ,terminalId:''
      },
      terminalLoadingProduct:false,
      terminalDataListProduct:[],
      selectedTerminalListProduct:[],


      userList:[],
      needGuohuList:[],
      guohuOpen:false,
      guohuForm:{
        targetUserId:null,
      },
      guohuRules: {
        targetUserId: [
          {required: true, message: "请选择用户名称", trigger: "change"}
        ]
      },
    };
  },
  created() {
    this.getTreeList();
    this.getUserList();
    // this.screenHeight = document.body.clientHeight
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  mounted() {
    this.getList();
    this.treeWidth = this.$refs['tree']?.$el.offsetWidth - 15
    // this.initTreeSelect();
  },
  methods: {
    toggleMaximize() {
      this.isFullscreen = !this.isFullscreen;

      // 你可以在这里添加一些额外的逻辑，比如记录窗口位置等
    },

    /** 查询租户用户信息-select */
    getUserList(){
        getUserListInSelect().then(response => {
          this.userList = response.data;
        });
    },
    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true;
      this.sheetsTreeList = JSON.parse(localStorage.getItem('meteredTreeData'))
      if (this.sheetsTreeList.length === 0){
        this.treeLoading = false;
      }else{
        this.defaultExpandedKeys = [this.sheetsTreeList[0].id];
        this.sheetsTreeList.map(item => {
          this.getLeafKeys(item)
        })
        this.treeLoading = false;
      }
    },
    getLeafKeys(node) {
      //判断是否要禁用的条件
      // if (node.deviceType === 0 && node.children.length === 0) {
      //   node.isDisabled = true
      // } else {
        node.isDisabled = false
      // }
      node.children.forEach(item => this.getLeafKeys(item))
    },
    handleNodeClick(data) {
      // this.queryParams.areaId = data.id;
      this.queryParams.sheetsCode = data.sheetsCode;
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.sheetsName.indexOf(value) !== -1;
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: '' + node.id,
        label: node.sheetsName,
        children: node.children,
        isDisabled: node.isDisabled
      };
    },
    // 区域下拉框改变触发事件
    handleSheetsChange(node) {
      this.form.areaId = node.id
    },
    initTreeSelect(){
     
      this.$nextTick(() => {
        this.form.areaId = this.sheetsTreeList[0].id
      });
       
    },
    //根据区域ID获取区域名称
    getAreaName(aId){
      let ll = this.sheetsTreeList;
      return this.recursiveAreaName(aId,ll);
    },
    recursiveAreaName(aId,list){
      let vv = "";
      for (let index = 0; index < list.length; index++) {
        const element = list[index];
        if(element.id == aId){
          return element.sheetsName;
        }else{
          if(element.children!=undefined && element.children.length>0){
            vv = this.recursiveAreaName(aId,element.children);
            if(vv !== ""){
              return vv;
            }
          }
        }
      }
      return vv;
    },

    /** 挂接start */

     //查询设备
    handleTerminalQueryProduct(){
      this.getTerminalDataListProduct();
    },
    /** 设备提交按钮 */
    terminalSubmitFormProduct() {
      addBindUser(this.selectedTerminalListProduct).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.getBindList();
              this.terminalOpenProduct = false;
            });
    },
    // 多选框选中数据
    handleSelectionChange2Product(selection) {
      let that = this;
      that.selectedTerminalListProduct = [];
      for(let i=0;i<selection.length;i++){
        let item = selection[i];
        that.selectedTerminalListProduct.push({
          publicShareId:that.selectedPublicShareId,
          terminalId:item.terminalId,
          userId:item.userId,
          locationNb:item.locationNb,
          energyType:that.powerType,
          publicShareType:that.publicShareType,
          calcType:item.calcType,
          status:item.terminalMark == 1 ? 1 : 2
        });
      }
    },
    // 设备取消按钮
    terminalCancelProduct() {
      this.terminalOpenProduct = false;
      this.terminalQueryParamsProduct = {pageNum: 1,
        pageSize: 20,
        userId:'',
        userName:''
        ,terminalId:'',
};
    },
    ///////////////////////////////////////////////////////////////////////////
    //用户
    //查询设备
    handleTerminalQuery(){
      this.getTerminalDataList();
    },
    /** 设备提交按钮 */
    terminalSubmitForm() {
      addBindUser(this.selectedTerminalList).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.getBindList();
              this.terminalOpen = false;
            });
    },
    // 多选框选中数据
    handleSelectionChange2(selection) {
      let that = this;
      that.selectedTerminalList = [];
      for(let i=0;i<selection.length;i++){
        let item = selection[i];
        that.selectedTerminalList.push({
          publicShareId:that.selectedPublicShareId,
          // terminalId:item.terminalId,
          userId:item.userId,
          // locationNb:item.locationNb,
          energyType:that.powerType,
          publicShareType:item.publicShareType,
          calcType:item.calcType,
          status:item.userMark == 1 ? 1 : 2
        });
      }
    },
    // 设备取消按钮
    terminalCancel() {
      this.terminalOpen = false;
      this.terminalQueryParams = {pageNum: 1,
        pageSize: 20,
        userId:'',
        userName:''};
    },
    /** 区域设备配置-新增打开弹框 */
    handleTerminalAdd() {
      if(this.publicShareType == 2){
        // this.terminalQueryParams = {pageNum: 1,
        //   pageSize: 20,
        //   userId:'',
        //   userName:''};
        // this.terminalOpen = true;
        // this.getTerminalDataList();
        this.handleTerminalAddConsume();
      }else if(this.publicShareType == 3){
        this.handleTerminalAddConstant();
      }else{
        this.handleTerminalAddProduct();
      }
      
    },
    handleTerminalAddConsume(){
      this.terminalQueryParams = {pageNum: 1,
          pageSize: 20,
          userId:'',
          userName:''};
      this.terminalOpen = true;
      this.getTerminalDataList();
    },
    handleTerminalAddProduct(){
      this.terminalQueryParamsProduct = {pageNum: 1,
          pageSize: 20,
          userId:'',
          userName:''
        , terminalId:''};
      this.terminalOpenProduct = true;
      this.getTerminalDataListProduct();
    },
    handleTerminalAddConstant(){
        let arrayConstant = [];
        let that = this;
        arrayConstant.push(
          {
          publicShareId:that.selectedPublicShareId,
          energyType:that.powerType,
          publicShareType: 3, // 生产常量
          status: 1 //在场
          }
        )
        addBindUser(arrayConstant).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.getBindList();
        });
    },
     /** 区域设备配置-新增打开弹框 */
    // handleTerminalAddConstant() {
    //   let arrayConstant = [];
    //   let that = this;
    //   //[{"publicShareId":23,"userId":"CS100001","energyType":"1","status":1}]
    //   arrayConstant.push({
    //     publicShareId:that.selectedPublicShareId,
    //     // userId:this.selectedTerminalList[0].userId,
    //     energyType:that.powerType,
    //     publicShareType: //3, 生产常量
    //     // status: 1 //在场
    //   })

    //   addBindUser(arrayConstant).then(response => {
    //       this.$modal.msgSuccess("新增成功");
    //       this.getBindList();
    //   });
    // },


    getTerminalDataList(){
      this.terminalLoading = true;
      // this.terminalQueryParams.areaOrPublicShare = 2;
      this.terminalQueryParams.publicShareId = this.selectedPublicShareId 
      // if(this.powerType == 1){
      //   listElecTerminalXb(this.terminalQueryParams).then(response => {
      //     this.terminalDataList = response.rows;
      //     this.terminalTotal = response.total;
      //     this.terminalLoading = false;
      //   });
      // }else{
      //   gjListTerminalxb(this.terminalQueryParams).then(response => {
      //     this.terminalDataList = response.rows;
      //     this.terminalTotal = response.total;
      //     this.terminalLoading = false;
      //   });
      // }
      getUserPageForGJ(this.terminalQueryParams).then(response => {
        this.terminalDataList = response.rows;
        this.terminalTotal = response.total;
        this.terminalLoading = false;
      });
    },
     getTerminalDataListProduct(){
      this.terminalLoadingProduct = true;
      this.terminalQueryParamsProduct.publicShareId = this.selectedPublicShareId 
      this.terminalQueryParamsProduct.energyType = this.powerType 
      getUserPageForGJProduct(this.terminalQueryParamsProduct).then(response => {
        this.terminalDataListProduct = response.rows;
        this.terminalTotalProduct = response.total;
        this.terminalLoadingProduct = false;
      });
    },
    // 区域设备配置
    handleSetting(row){
      this.isFullscreen = false;

      this.setTitle="["+row.publicShareName+"]公摊设备挂接";
      this.setOpen = true;
      this.selectedPublicShareId = row.id;
      this.selectedPublicShareName = row.publicShareName;
      // this.powerType = '1';
      this.publicShareType = '';
      this.getBindList();
    },
    /** 删除按钮操作-区域设备配置 */
    handleBindTerminalDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除所选记录？').then(function () {
        return delPublicShareJoin(id);
      }).then(() => {
        this.getBindList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleChange1(val){
      
      this.powerType = val+'';
      console.log(this.powerType);
    },
    //区域设备配置-选择能耗类型
    handleEnergyTypeChange(val){
      this.powerType = val+'';
      this.getBindList();
    },
    handleUserIdChange(val){
      this.userId = val+'';
      this.getBindList();
    },
     handleTerminalIdChange(val){
      this.terminalId = val+'';
      this.getBindList();
    },
    handlePublicShareTypeChange(val){
      this.publicShareType = val+'';
      this.getBindList();
    },
    getBindList(){
      //加载数据
      this.setLoading = true;
      listPublicShareJoinAll(Object.assign(this.terminalQueryParamsSetting
        ,{publicShareId:this.selectedPublicShareId,energyType:this.powerType
          ,publicShareType:this.publicShareType
          ,userId:this.userId
          ,terminalId:this.terminalId
      }
      )).then(response => {
        this.setDataList = response.rows;
        this.terminalTotalSetting = response.total;
        this.setLoading = false;
      });
      
      // listPublicShareJoinAll({publicShareId:this.selectedPublicShareId,energyType:this.powerType
      //     ,publicShareType:this.publicShareType

      // }).then(response => {
      //   if(response.data){
      //     this.setDataList = response.data;
      //   }
      //   this.setLoading = false;
      // });
    },
    handleEditChange(row){
      //TODO 1 2 禁止修改位3   3禁止修改为2
      // if(row.publicShareType  === 1  || row.publicShareType  === 2){

      // }
      editBindUser(row).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.getBindList();
      });
    },
    /** 挂接end */

    /** 查询公摊配置表列表 */
    getList() {
      this.loading = true;
      listPublicShare(this.queryParams).then(response => {
        this.publicShareList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tenantId: null,
        areaId: null,
        publicShareName: null,
        energyType: '1'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.needGuohuList = selection;
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.initTreeSelect();
      this.open = true;
      this.title = "添加公摊配置表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPublicShare(id).then(response => {
        this.form = response.data;
        this.form.energyType = this.form.energyType + '';
        this.open = true;
        this.title = "修改公摊配置表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePublicShare(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPublicShare(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除公摊配置表编号为"' + ids + '"的数据项？').then(function() {
        return delPublicShare(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('datastatistics/publicShare/export', {
        ...this.queryParams
      }, `publicShare_${new Date().getTime()}.xlsx`)
    },
    /** 一键过户 */
    handleGuohu(){
      this.guohuForm = { targetUserId: null };
      this.resetForm("guohuForm");
      let hasDiffrentUser = false;
      this.needGuohuList.forEach(item =>{
        if(item.gjUserIds ==null || item.gjUserIds.indexOf(this.queryParams.userId) === -1){
          hasDiffrentUser = true;
        }
      });
      if(!hasDiffrentUser){
        this.guohuOpen = true;
      }else{
        this.$modal.msgError("存在部分公摊未挂接选择的用户，请先选择用户，再搜索！");
      }
    },
    submitGuohuForm() {
      this.$refs["guohuForm"].validate(valid => {
        if (valid) {
          this.guohuForm.sourceUserId = this.queryParams.userId;
          this.guohuForm.publicShareIds = this.needGuohuList.map(item => item.id);
          transferPublicShare(this.guohuForm).then(response => {
            this.$modal.msgSuccess("过户成功");
            this.guohuOpen = false;
            this.getList();
          });
        }
      });
    },
    guohuCancel() {
      this.guohuOpen = false;
      this.guohuForm = { targetUserId: null };
      this.resetForm("guohuForm");
    },
  }
};
</script>

<style scoped lang="scss">
.div-height-minus{
  height: 500px;
}
.div-height-full-screen{
 height:  calc(100vh - 150px);
}


/* 自定义标题栏的布局 */
.custom-dialog-header {
  display: flex;
  justify-content: space-between; /* 标题和按钮组两端对齐 */
  align-items: center;           /* 垂直居中 */
  width: 100%;                   /* 确保占据整个标题栏宽度 */
}

/* 自定义标题文本样式 */
.custom-dialog-title {
  font-size: 16px;
  // font-weight: 700;
  color: var(--el-text-color-primary); /* 使用 Element UI 的主题变量 */
  line-height: 1;
}

/* 自定义操作按钮组 */
.custom-dialog-actions {
  display: flex;
  gap: 6px; /* 按钮之间的间距 */
}

/* 
 * 自定义按钮的基础样式
 * 模仿 Element UI 原始关闭按钮的尺寸和行为
 */
.custom-dialog-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  margin: 0;
  color: var(--el-text-color-placeholder); /* 默认颜色偏灰 */
  border-radius: 50%; /* 圆形按钮更美观 */
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease; /* 平滑过渡效果 */
}

/* 鼠标悬停时的样式 */
.custom-dialog-btn:hover {
  color: var(--el-color-primary); /* 悬停时变为主题色 */
  background-color: var(--el-color-primary-light-9); /* 轻微的背景色变化 */
}

/* 
 * 特别为关闭按钮添加样式
 * 如果你想让关闭按钮和最大化按钮在视觉上有所区分，可以单独设置
 */
.custom-dialog-close-btn:hover {
  color: var(--el-color-danger); /* 例如，让关闭按钮悬停时显示警告色 */
  background-color: var(--el-color-danger-light-9);
}


/* 核心样式：让自定义标题区域与操作按钮区水平排列 */
// .el-dialog__header {
//   display: flex;
//   align-items: center;
// }

// .custom-dialog-header {
//   flex: 1; /* 关键：让标题区域占据剩余的所有空间 */
//   display: flex;
//   justify-content: space-between; /* 让标题文字和自定义按钮分开 */
//   align-items: center;
//   padding-right: 16px; /* 增加一些与关闭按钮的间距 */
// }


// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node {
    width: fit-content;
    min-width: var(--treeWidth);
  }

  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;

    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }
  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }
}
.form_col {
  width: 80%;

  ::v-deep .el-form {
    width: 100%;
  }

  ::v-deep .el-form-item {
    width: 23%;
  }
}
.form_query {
  width: 20%;
  text-align: right;
}
</style>